package com.five.sso.service.impl;

import cn.hutool.core.util.StrUtil;
import com.five.core.exception.CustomerException;
import com.five.core.result.ResultEnum;
import com.five.sso.repository.UserRepository;
import com.five.sso.service.SendMsgService;
import com.five.sso.utils.AliyunSmsVerifyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class SendMsgServiceImpl implements SendMsgService {

    public static final Integer REP_MSG_EXPIRE = 5 * 60;
    public static final String REP_MSG = "USER_REP_MSG";
    public static final String LONG_MSG = "USER_LONG_MSG";
    public static final String ONE_LOGIN_MSG = "USER_ONE_LONG_MSG";

    @Resource
    private UserRepository userRepository;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private AliyunSmsVerifyUtils aliyunSmsVerifyUtils;

    @Override
    public void sendRegisterMsg(String phone) {
        if (StrUtil.isEmpty(phone)) {
            log.info("手机号不能为空");
            throw new CustomerException(ResultEnum.NOT_PHONE_ENTITY);
        }
        if (userRepository.findUserByPhone(phone) != null) {
            log.info("手机号已存在");
            throw new CustomerException(ResultEnum.PHONE_EXIT);
        }
        cheackCode(phone, REP_MSG);
        sendCode(phone, REP_MSG);
    }

    @Override
    public void sendLoginMsg(String phone) {
        if (StrUtil.isEmpty(phone)) {
            log.info("手机号为空");
            throw new CustomerException(ResultEnum.NOT_PHONE_ENTITY);
        }
        if (userRepository.findUserByPhone(phone) == null) {
            log.info("手机号不存在");
            throw new CustomerException(ResultEnum.NOT_USER_PHONE);
        }
        cheackCode(phone, LONG_MSG);
        sendCode(phone, LONG_MSG);
    }

    @Override
    public void sendOneLoingMsg(String phone) {
        if (StrUtil.isEmpty(phone)) {
            log.info("手机号为空");
            throw new CustomerException(ResultEnum.NOT_PHONE_ENTITY);
        }
//        cheackCode(phone, ONE_LOGIN_MSG);
        sendCode(phone, ONE_LOGIN_MSG);
    }

    private void sendCode(String phone, String key){
        String code = String.format("%04d", (int) (Math.random() * 10000));
        redisTemplate.opsForValue().set(key+phone,code,REP_MSG_EXPIRE, TimeUnit.SECONDS);
        log.info("发送验证码:"+code);
        try {
            //开启发送短信
          //  aliyunSmsVerifyUtils.sendSmsVerifyCode(phone,code);
        } catch (Exception e) {
            log.warn(e.getMessage());
        }
    }

    private void cheackCode(String phone, String key){
        String code =(String) redisTemplate.opsForValue().get(key + phone);
        if (code != null){
            log.info("验证码已过期");
            throw new CustomerException(ResultEnum.CODE_IS_EMPTY);
        }
    }
}
